﻿using Microsoft.Extensions.Configuration;
using Serilog;
using Syspetro.Core.AppDeal;
using Syspetro.Core.Extensions;
using Syspetro.Core.HttpService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Syspetro.DepConsul
{
    public class ConsulClientHelper
    {
        readonly IConfiguration _IConfiguration = null;
        readonly AbstractConsulDispatcher _IConsulDispatcher = null;
        readonly HttpHelper _httpHelperService = null;
        public ConsulClientHelper(IConfiguration configuration, AbstractConsulDispatcher consulDispatcher, HttpHelper httpHelperService)
        {
            this._IConfiguration = configuration;
            this._IConsulDispatcher = consulDispatcher;
            this._httpHelperService = httpHelperService;
        }
        public async Task<T> HttpRequestAsync<T>(string url, HttpMethod httpMethod, Dictionary<string, string> param = null)
        {
            string realUrl = this._IConsulDispatcher.GetAddress(url);
            var response = await _httpHelperService.HttpRequestAsync(realUrl, httpMethod, param);
            return GetResult<T>(response, url, param.ToString());
        }
        public async Task<T> HttpRequestAsync<T>(string url, HttpMethod httpMethod, string param = null)
        {
            string realUrl = this._IConsulDispatcher.GetAddress(url);
            var response = await _httpHelperService.HttpRequestAsync(realUrl, httpMethod, param);
            return GetResult<T>(response, url, param);
        }
        public async Task<T> GetHttpCal<T>(string dataRep, string configUrl = "VerifyUserUrl", string routeUrl = "ServiceApp/Cal")
        {
            string requestUrl = $"{this._IConfiguration[configUrl]}{routeUrl}";
            var date = await HttpRequestAsync<SpActionResult<T>>(requestUrl, HttpMethod.Post, dataRep);
            if (date == null)
            {
                Log.Error("接口通讯异常");
                throw new Exception("接口通讯异常");
            }
            else if (!date.Success)
            {
                Log.Error(date.Msg);
                throw new Exception(date.Msg);
            }
            else
            {
                return date.Data;
            }
        }
        private static T GetResult<T>(HttpResponseMessage response, string url, string param)
        {
            if (response.IsSuccessStatusCode)
            {
                var date = response.Content.ReadAsStringAsync().Result;
                return date.ToObject<T>();
            }
            else
            {
                Log.Error($"{url}请求失败;状态码:{response.StatusCode};参数:{param};");
            }
            return default;
        }
    }
}
